import { defineStore } from 'pinia'

interface Countdown {
  endTime: number
  timer?: number
}

export const useCounterStore = defineStore('counter', {
  // 仓库状态定义
  state: () => ({
    // 使用Map存储多个订单的倒计时，key为订单号，value为倒计时对象
    countdowns: new Map<string, Countdown>(),
  }),
  actions: {
    // 初始化倒计时
    initCountdown(orderNumber: string, initialSeconds: number) {
      if (!this.countdowns.has(orderNumber)) {
        const endTime = Date.now() + initialSeconds * 1000 // 计算结束时间戳
        this.countdowns.set(orderNumber, {
          endTime,
          // 创建定时器，每秒更新倒计时
          timer: setInterval(() => this.updateCountdown(orderNumber), 1000),
        })
      }
    },

    // 更新倒计时状态
    updateCountdown(orderNumber: string) {
      const countdown = this.countdowns.get(orderNumber)
      // 检查是否到达结束时间
      if (countdown && Date.now() >= countdown.endTime) {
        this.clearCountdown(orderNumber)

        // 这里可以触发超时后的操作（例如订单超时逻辑）
      }
    },

    // 持久化倒计时到本地存储
    persistCountdown(orderNumber: string) {
      const countdown = this.countdowns.get(orderNumber)
      if (countdown) {
        // 将结束时间存入localStorage
        uni.setStorageSync(orderNumber, countdown.endTime.toString())
      }
    },

    // 获取剩余秒数
    getRemainingSeconds(orderNumber: string): number {
      // 尝试从本地存储读取
      const stored = uni.getStorageSync(orderNumber)
      // 优先使用内存中的倒计时，不存在则尝试从存储恢复
      const countdown =
        this.countdowns.get(orderNumber) ||
        (stored && {
          endTime: parseInt(stored),
          timer: undefined,
        })

      if (countdown) {
        // 计算剩余时间（秒）
        const remaining = Math.max(0, Math.round((countdown.endTime - Date.now()) / 1000))
        // 清除已完成的倒计时
        if (remaining === 0) this.clearCountdown(orderNumber)
        return remaining
      }
      return 0
    },

    // 清除指定订单的倒计时
    clearCountdown(orderNumber: string) {
      const countdown = this.countdowns.get(orderNumber)
      if (countdown?.timer) {
        clearInterval(countdown.timer) // 清除定时器
      }
      this.countdowns.delete(orderNumber) // 从Map中移除
      uni.removeStorageSync(orderNumber) // 移除本地存储
    },
  },
})
